package com.example.service;

import com.example.entity.Order;
import io.camunda.zeebe.client.api.response.ActivatedJob;
import io.camunda.zeebe.spring.client.annotation.JobWorker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 库存扣减工作器（Camunda 流程任务）
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InventoryService {

    private final OrderService orderService;

    @JobWorker(type = "deduct-inventory", autoComplete = true)
    public void deductInventory(ActivatedJob job) {
        String orderNo = job.getVariablesAsMap().get("orderNo").toString();
        log.info("开始扣减订单库存：{}", orderNo);

        // 1. 获取订单信息（商品数量）
        Order order = orderService.getOrderByNo(orderNo);
        int productCount = order.getProductCount();

        // 2. 模拟库存扣减（实际场景对接库存系统）
        boolean inventoryEnough = true;  // 模拟库存充足
        if (!inventoryEnough) {
            throw new RuntimeException("订单库存不足：" + orderNo + "，需扣减：" + productCount);
        }

        // 3. 更新订单状态为「库存扣减完成」
        orderService.updateOrderStatus(orderNo, Order.OrderStatus.INVENTORY_DONE);
        log.info("订单库存扣减完成，状态更新为 INVENTORY_DONE：{}", orderNo);
    }
}